package util.tools;
import constant.Constant;
import constant.WebCityId;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import test_achieve.Devices;
import test_achieve.LogRead;
import test_achieve.courierapp.Courier;
import test_achieve.courierapp.GrabOrder;
import test_achieve.courierapp.HttpCourier;
import test_achieve.courierapp.Oneself;
import util.*;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenkuo on 2018/1/4.
 */
public class BusinessTools {
    /**
     * 等待抢单按钮出现
     */

    public static boolean waitGrabButton(WebDriver driver, String by) {
        WebDriverWait wait = new WebDriverWait(driver, 15);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.id(by)));
        return true;
    }

    public static int amountComparison(String UserBalance, String OrderActualAmount, String orderFareIncrease) {
        int expect = Integer.parseInt(UserBalance) - Integer.parseInt(orderFareIncrease);//理论余额=下单后余额-加价金额
        return expect;
    }

    public static String buildPicCaptcha() {
        Calendar currentDate = new GregorianCalendar();
        currentDate.set(Calendar.HOUR_OF_DAY, 0);
        currentDate.set(Calendar.MINUTE, 0);
        currentDate.set(Calendar.SECOND, 0);
        currentDate.set(Calendar.MILLISECOND, 0);
        String str = String.valueOf(currentDate.getTime().getTime() / 100000);
        str = str.substring(str.length() - 4);
        return str;
    }


    /**
     * 闪送员现金账户金额核对
     */
    public static BigDecimal courierMoneyCheck() {
        BigDecimal courierGeneralIncom = courierGeneralIncom();//闪送员订单总收入（未抽佣）
        BigDecimal SendGeneralIncome = new BigDecimal(Constant.sendGeneralTotalIncome);
        BigDecimal chouyong = new BigDecimal("0.8");
        BigDecimal baoxian = new BigDecimal("0.3");
        BigDecimal courierBalance = courierGeneralIncom.multiply(chouyong).subtract(SendGeneralIncome).subtract(baoxian);
        /* 闪送员现金收入=闪送员订单总收入（未抽佣）-抽佣金额-保险金额-寄付到付闪送员订单理论收入（未抽佣）*/
        return courierBalance.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public static String phoneNumberLatterFour(String str) {
        String number = str.substring(str.length() - 4, str.length());
        return number;
    }

    /**
     * 闪送员订单总收入（未抽佣）
     */
    private static BigDecimal courierGeneralIncom() {
        BigDecimal OrderAmount = new BigDecimal(Constant.orderAmount);//订单总额
        BigDecimal orderMoto = new BigDecimal(Constant.orderMoto);//摩托车金额
        BigDecimal FareIncrease = new BigDecimal(Constant.orderFareIncrease);
        System.out.println("摩托车金额" + orderMoto);
        System.out.println("订单加价金额" + FareIncrease);
        /* 闪送员订单总收入（未抽佣）=订单总额-摩托车未穿透费用 +订单加价金额*/
        BigDecimal result = OrderAmount.subtract(orderMoto);//为什么没有加价金额
        return result;
    }

    /**
     * 扫尾初始化数据
     */
    public static void initParam() {
        Constant.orderFareIncrease = "0";
        Constant.orderMoto = 0;
        Constant.userBalance = "0";
        Constant.orderAmount = "0";
        Constant.orderBalancePayAm = "0";
        Constant.orderFarePremium = "0";
        Constant.sendGeneralTotalIncome = 0;
        Constant.courierBalance = 0;
        Constant.OrderNumbuter.clear();
        Constant.testReport.clear();
        Constant.interfaceGrabStatus = false;
//        Constant.evn = null;
    }


    /**
     * 闪送员端deiver启动，不通过设备号
     * 场景：单独app真机测试
     */
    public static boolean startCourierApp(String number) throws Throwable {
        Devices devices = new Devices();
        Boolean longinedStart = true;
        try {
            devices.longinedOpenCourierApp();//默认已登录状态下启动，如果报错则用未登录状态下启动
            System.out.println("已登录状态下启动");
            Thread.sleep(4000);
            Boolean A = CommonTools.checkElementExit(Constant.driverCourier, By.id("img_refresh"));
            System.out.println("已登录状态下启动："+A);
            if (!(CommonTools.checkElementExit(Constant.driverCourier, By.id("img_refresh")))) {
//                System.out.println("元素没有找到，肯定是需要登录页面登录");
                throw new RuntimeException("未找到指定元素，非登录状态启动");
            }{
                BusinessTools.checkCourierAccount(number);
            }

        } catch (Exception e) {
            quitCourierDriver();
            longinedStart = false;
            devices.notLonginOpenCourierApp();//未登录界面启动
            Courier courier = new Courier();
            courier.couierLogin(number);//闪送员登录
        }
        System.out.println("启动是否为登录启动：" + longinedStart);
        return longinedStart;
    }

    public static void quitCourierDriver() {
        if (Constant.driverCourier != null) {
            Constant.driverCourier.quit();
            Constant.driverCourier = null;
        }
    }

    /**
     * 闪送员端，检查当前登录账户是否与预期一致
     *如果不一致则切换到预期账户
     */
    public static void checkCourierAccount(String number) throws Throwable {
//        Boolean checkCourierAccount = true;
        Oneself my = new Oneself();
        checkEvn(number);
        my.进入我的闪送页面();
        String str = Constant.driverCourier.findElement(By.id("user_name")).getText();
        String number1 = str.substring(str.length() - 4, str.length());
        String number2 = number.substring(number.length() - 4, number.length());
        if (!(number1.equals(number2))) {//对比手机号后4位是否相等
            GrabOrder grabOrder = new GrabOrder();
            grabOrder.logOut();
            Courier courier = new Courier();
            courier.couierLogin(number);
        }
//        System.out.println("当前账户是否与预期一致：" + checkCourierAccount);

    }
    /**
     * 判断是不是想测试环境，如果不是则进行环境切换
     */
    public static void checkEvn(String number) throws Throwable {
        String evn = null;
        Oneself my = new Oneself();
        my.进入闪送员主页面();
        String nowEvn = Constant.driverCourier.findElement(By.id("com.ishansong:id/title_txt")).getText();
        System.out.println("当前的环境："+nowEvn);
        System.out.println("想要切换的环境："+Constant.evn);
        if (Constant.evn.equals("stable")){
             evn = "prepare";
        }else {
            evn = Constant.evn;
        }
        switch(nowEvn){
            case "prepare":
                if (!(Constant.evn.equals("stable"))){
                    switchEvn (evn,number);
                }
                break;
            case "sstable":
                if (!(Constant.evn.equals("sstable"))){
                    switchEvn (evn,number);
                }
                break;
            case "fstable":
                if (!(Constant.evn.equals("fstable"))){
                    switchEvn (evn,number);
                }
                break;
        }

    }
    /**
     * 闪送员端环境切换
     * 前置：当前为闪送员主页面
     */

    public static void switchEvn(String evn,String number) throws Throwable {
        Constant.driverCourier.findElement(By.id("com.ishansong:id/title_txt")).click();
        Constant.driverCourier.findElement(By.name(evn)).click();
        CommonTools.swipeUp(Constant.driverCourier);
        CommonTools.swipeUp(Constant.driverCourier);
        Constant.driverCourier.findElement(By.id("btn_save")).click();
        Constant.driverCourier.quit();
        Devices devices = new Devices();
        devices.notLonginOpenCourierApp();
        Courier courier = new Courier();
        courier.couierLogin(number);

    }

    /**
     * 闪送员端deiver启动，通过服务、设备号启动
     * 场景：多机、模拟器测试
     */
    public static void startCourierApp(String number, String server, String uuid) throws Throwable {
//        System.out.println("Constant.driverCourier" + Constant.driverCourier);
        String s = Constant.driverCourier + "";
        if (!s.contains("null")) {
            loginReady(number);

        } else {
            Constant.driverCourier = InitDrivers.getssyDriverWithLogined(server, uuid);
            Boolean b = Constant.driverCourier.findElement(By.id("title_txt")).getText().equals("闪送");
            if (!b) {//如果driver启动后，直接在 已登录页面，则，不再进行登录操作，否则，进行下面的登录操作
                Constant.driverCourier.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);//查找元素超时时间10秒
                Courier courier = new Courier();
                courier.couierLogin(number);
            }

        }
    }

    /**
     * 如果driver存在，切换到闪送员主页面的操作
     * number：手机号
     */
    private static void loginReady(String number) throws Throwable {
        Oneself my = new Oneself();
        my.进入我的闪送页面();
        if (!(CommonTools.checkElementExit(Constant.driverCourier, "id", "user_name"))) {
            Constant.driverCourier.quit();
            Devices devices = new Devices();
            devices.notLonginOpenCourierApp();
            loginReady(number);
        }
        String str = Constant.driverCourier.findElement(By.id("user_name")).getText();
        String number1 = str.substring(str.length() - 4, str.length());
        String number2 = number.substring(number.length() - 4, number.length());
        if (number1.equals(number2)) {//对比手机号后4位是否相等
            my.进入闪送员主页面();
        } else {
            GrabOrder grabOrder = new GrabOrder();
            grabOrder.logOut();
            Courier courier = new Courier();
            courier.couierLogin(number);
        }

    }


    /**
     * 接口判断订单状态
     */

    public static void checkOrderStatus(String orderNumber, int orderStatus) {
        int orderStatu = JdbcUtil.sqlInt(ConfigSql.get("queryorder2status", orderNumber));
        org.testng.Assert.assertEquals(orderStatu, orderStatus);
    }

    /**
     * 接口获取闪送员身上的订单
     */

    public static String getDispatchOrderNum(String courierNum) {
        String courierId = JdbcUtil.sqlString(ConfigSql.get("queryUser1CourierId", courierNum));
        if (courierId == null) {
            courierId = JdbcUtil.sqlString(ConfigSql.get("queryUser2CourierId", courierNum));
        }
        System.out.println("courierId:" + courierId);
        String orderNumber = JdbcUtil.sqlString(ConfigSql.get("queryCourierOrderNumber", courierId));
        return orderNumber;
    }


    /**
     * 脱敏
     * 传入手机号获取密文
     */
    public static String getMobileSecret(String mobile) {
        String url = Constant.mobileSecret + mobile;
//        String url ="http://dest.sf.bingex.com/rest/encrypt/"+mobile;
        String s = HttpClient.get(url, null, null);
//        System.out.println("获取到的密文："+s);
        return CommonTools.cutMiddle(s, "a\":\"", "\",\"err");

    }

    /**
     * 脱敏链接检查，如果检查失败自动化终止
     */
    public static void checkMobileSecret() {
        try {
            getMobileSecret("15501213579");
        } catch (Exception e) {
            System.out.println("自动化前置检查失败：手机号无法脱敏，请把电脑wifi断开后重新开启，之后再进行自动化测试，谢谢");
            System.exit(1);
        }
    }

    /**
     * 基本计费策略检查，如果检查失败自动化终止
     * 预约费、溢价检查
     */
    public static void checkPrice() throws Throwable {
//        Constant.evn = "sstable";
//        ConfigLoader.load(Constant.evn+".properties");
//        Devices devices = new Devices();
//        devices.openBrowser();
//        OrderMain orderMain = new OrderMain();
//        orderMain.wLogInEnterInterface("131268514111");
//        orderMain.wSwitchCity("北京市");
//        Basic basic = new Basic();
//        basic.w输入寄件人信息与收件人信息("昌平西山口","西二旗");
//        orderMain.w输入物品名称();
//        orderMain.w选择预约取件取件时间("04");
//        orderMain.wClickNext();
//        orderMain.wConfirmTotalOrder(46);
//        WebPrice webPrice = new WebPrice();
//        webPrice.w提交界面确认订单总额("46");
//        Constant.driverWeb.quit();
//        Constant.driverWeb = null;

    }

//    public static void main(String[] args) {
//        System.out.println(BusinessTools.getMobileSecret("16611111111"));
////        checkMobileSecret();
//    }

    /**
     * 推送排除网络影响
     */
    public static void pushExcludeNetworkImpact(String user) throws Throwable {
        System.out.println("推单失败，开始查日志分析");
        LogRead logRead = new LogRead();
        String orderNum = Constant.OrderNumbuter.get(Constant.OrderNumbuter.size() - 1);
        System.out.println("订单号" + orderNum);
        boolean isPushGexin = logRead.r筛选今天push_推送日志(orderNum, user);
        boolean isPushChannel = logRead.r筛选今天distribute_调度日志(orderNum, user);
        if (isPushGexin || isPushChannel) {
            HttpCourier httpCourier = new HttpCourier();
            System.out.println("开始进行接口抢单....");
            httpCourier.p抢单成功(user);
            Constant.interfaceGrabStatus = true;
            Oneself oneself = new Oneself();
            oneself.进入闪送员主页面();
            oneself.刷新订单信息();
            oneself.主页面点击第一个订单();
        }

    }

    /**
     * 从redis中获取Web端的图形验证码
     * 各个页面获取图形验证码
     */
    //  IOS_LOGIN("IOS_login","IOS端账号登录"),
//    ANDROID_LOGIN("android_login","android端账号登录"),
//    PC_LOGIN("pc_login","pc端账号登录"),
//    WX_LOGIN("_wx_login","微信端账号登录"),
//
//    IOS_REGISTER("IOS_register","IOS端注册"),
//    ANDROID_REGISTER("android_register","android端注册"),
//    PC_REGISTER("pc_register","pc端注册"),
//    WX_REGISTER("wx_register","微信端注册"),
//
//
//    IOS_SMSLOGIN("IOS_smsLogin","IOS端短信登录"),
//    ANDROID_SMSLOGIN("android_smsLogin","android端短信登录"),
//    PC_SMSLOGIN("pc_smsLogin","pc端短信登录"),
//    WX_SMSLOGIN("_wx_smsLogin","微信端短信登录");

    public static String getWebGraphicalCaptcha(WebDriver driver, String type) throws UnknownHostException {
        String cookies = driver.manage().getCookies().toString();
//        System.out.println(cookies);
        String cookieCut = CommonTools.cutEnd(cookies, "issUserUUID=");
        String issUserUUID = CommonTools.cutFront(cookieCut, "; expires=");//从cookie中获取
//        System.out.println("issUserUUID："+issUserUUID);
        Jedis jedis = connectRedis();
        String key = "captcha_v1_" + issUserUUID + type;
//        System.out.println("验证码key：" + key);
        String value = jedis.get(key);
        System.out.println("验证码为：" + value);
        return value;
    }

    public static String getH5GraphicalCaptcha(WebDriver driver, String type) throws UnknownHostException {
//        String cookies = driver.manage().getCookies().toString();
        String issUserUUID = driver.manage().getCookieNamed("issUserUUID").getValue();
//        System.out.println("issUserUUID:"+issUserUUID);
//        System.out.println(cookies);
//        String cookieCut = CommonTools.cutEnd(cookies, " huid=");
//        String issUserUUID = CommonTools.cutFront(cookieCut, "; expires=");//从cookie中获取
//        System.out.println(issUserUUID);
        Jedis jedis = connectRedis();
        String key = "captcha_v1_" +issUserUUID + type;
        System.out.println("验证码key：" + key);
        String value = jedis.get(key);
        System.out.println("验证码为：" + value);
        return value;
    }

    /**
     *从redis中删除登录的限制
     *WEIXIN:wx_USER
     * PC:pc_USER
     */
    public static void removeLoginNum(String mobile,String type) throws UnknownHostException {
        Jedis jedis = connectRedis();
        String localhost = InetAddress.getLocalHost().getHostAddress();
        String key = mobile+"_"+type+"_USER_login_locked";
        String key1 = mobile+"_"+type+"_USER_login_captcha_count";
        String key2 = localhost+"_"+type+"_USER_login_captcha_count";
//        System.out.println(key);
//        System.out.println(key1);
//        System.out.println(key2);
        jedis.del(key);
        jedis.del(key1);
        jedis.del(key2);
//        System.out.println(jedis.get(key));
//        System.out.println(jedis.get(key1));
//        System.out.println(jedis.get(key2));

    }
    /**
     * */
    public static void removeCouponRedis(String mobile) throws UnknownHostException {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Jedis jedis = connectRedis();
        String key = "coupon.redbag.count.614."+mobile+"";
        String aa = Constant.driverWeb.manage().getCookies().toString();
        System.out.println(aa);
        String cookie = Constant.driverWeb.manage().getCookieNamed("issMvtUUID").toString();
        String issMvtUUID = CommonTools.cutMiddle(cookie,"issMvtUUID=","; expires=");
        System.out.println("issMvtUUID:"+cookie);
        String key1 = "coupon.device.redbag.count.614."+issMvtUUID+"";
        System.out.println("hahahahhaha:"+jedis.get(key).toString());
        System.out.println("hahaha222222:"+jedis.get(key1).toString());
        jedis.del(key);
        jedis.del(key1);
        }


    public static void main(String[] args) throws UnknownHostException {
        removeLoginNum("13126642902","pc_USER");
    }
    /**
     * 链接redis
     */
    public static Jedis connectRedis() throws UnknownHostException {
        JschManager.init();
        InetAddress localhost = InetAddress.getLocalHost();
        JedisPool jedisPool = new JedisPool(localhost.getHostAddress(), 3308);
        Jedis jedis = jedisPool.getResource();
        return jedis;
    }

    public static void menuCityChoice(String city) throws Exception {
        Thread.sleep(2000);
        CommonTools.waitElementLoad(Constant.driverWeb,"xpath","//*[@id=\"cityList\"]/li["+ WebCityId.getCityCodeByName(city)+"]");
        WebElement city3 = Constant.driverWeb.findElement(By.xpath("//*[@id=\"cityList\"]/li["+ WebCityId.getCityCodeByName(city)+"]"));//因为有bug导致需要选择城市
//        System.out.println(city);
        city3.click();
        Thread.sleep(3000);
    }



}
